package com.huima.blog.controller;

import com.huima.blog.service.AdminFileService;
import com.huima.blog.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

/**
 * @description: TODO
 **/
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminFileController {

    @Autowired
    private AdminFileService fileService;

    @PostMapping("/file/upload")
    public Response uploadFile(@RequestParam MultipartFile file) {
        return fileService.uploadFile(file);
    }


    @GetMapping("/view")
    public void view(String imgUrl, HttpServletResponse response) {
        String rootPath = getProjectRootDirectory();
        FileInputStream fis = null;
        ServletOutputStream os = null;
        try {
            fis = new FileInputStream(rootPath + "/src/main/resources/img/" + imgUrl);
            os = response.getOutputStream();
            byte[] b = new byte[1024];
            while (fis.read(b) != -1) {
                os.write(b);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String getProjectRootDirectory() {
        // 获取当前类的ClassLoader
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader != null) {
            try {
                // 获取当前类的URL地址
                URL url = loader.getResource("");

                if (url != null && "file".equalsIgnoreCase(url.getProtocol())) {
                    // 将URL转换成File对象
                    File file = new File(url.toURI());

                    // 返回上两级目录 (当前目录为classes,上一级为target,再上一级为项目路径)
                    return file.getParentFile().getParentFile().getAbsolutePath();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return "";
    }
}
